package com.huiyeji.dynamic.core;


import com.huiyeji.dynamic.core.provider.DynamicMethodProvider;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author Huiyeji
 */
public class DynamicObject {

    private final DynamicObjectInfo info;

    private final DynamicMethodProvider methodProvider;

    public DynamicObject(DynamicObjectInfo dynamicObjectInfo, DynamicMethodProvider methodProvider){
        this.info = dynamicObjectInfo;
        this.methodProvider = methodProvider;
    }

    public Object invoke(String methodName,Object... args) throws InvocationTargetException, IllegalAccessException {
        Class<?>[] paramTypes = new Class[args.length];
        for (int i = 0; i < args.length; i++) {
            paramTypes[i] = args[i] == null ? null : args[i].getClass();
        }
        Method method = methodProvider.get(new MethodRequest(getDynamicObjectName(),methodName,paramTypes));
        if (method == null){
            throw new NullPointerException("The dynamic object 【"+info.getName()+"】 has not registered the dynamic method 【"+methodName+"】");
        }

        return method.invoke(info.getObject(),args);
    }

    public void setDynamicObjectName(String name){
        this.info.setName(name);
    }

    public String getDynamicObjectName() {
        return info.getName();
    }

    public Object getObject() {
        return info.getObject();
    }
}
